/**
 * 
 */
package com.goktech.commons.excel.utils;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.goktech.commons.excel.utils.abs.AbstractIRowReader;
import com.goktech.commons.excel.utils.abs.AbstractReader;
import com.goktech.commons.excel.utils.filter.RowFileter;

/**
 * @author 24252
 *
 */
public class RowReaderFactory<T> extends AbstractIRowReader {

	private Logger logger = LoggerFactory.getLogger(getClass());

	public AbstractReader<T> reader;
	
	private RowFileter rowFileter;

	private int titleLegnth = 0;

	public RowReaderFactory(AbstractReader<T> reader) {
		this.reader = reader;
		this.rowFileter = new RowFileter();// 初始化空字符串过滤器
	}

	@Override
	public void getRows(int sheetIndex, int curRow, List<String> rowlist) {
		if (rowlist == null || rowlist.size() == 0) {
			return;
		}
		if (rowFileter.nullFileter(rowlist)) {// 判断空行
			if(curRow != 0 && titleLegnth != 0)	
			rowlist = rowFileter.Center(titleLegnth, rowlist);// 截取多余的列
		} else {
			return;
		}
		if (curRow == 0) {
			rowlist = rowFileter.subEndEmpty(rowlist);
			this.titleLegnth = rowlist.size();
			if (logger.isDebugEnabled())
				logger.debug("表头长度初始化成功，length:{}", titleLegnth);
			readerTitle(rowlist);
			time.set(System.currentTimeMillis());
		} else {
			List<String> tmpList = new ArrayList<>(rowlist.size());
			tmpList.addAll(rowlist);
			readerData(tmpList);
			if (countInteger.incrementAndGet() % 1000 == 0) {
				logger.info("当前已经解析 {} 行数据,任务队列 - {} 用时 {} 秒 ", countInteger.get(),this.atomicInteger.get(),
						(System.currentTimeMillis() - time.get()) * 1.0 / 1000);
			}
		}
	}

	@Override
	public boolean isEnd() {
		return this.atomicInteger.get() == 0;
	}

	@Override
	public void shutDown() {
		this.cachedThreadPool.shutdown();
	}

	private void readerTitle(List<String> rowList) {
		if (logger.isDebugEnabled())
			logger.debug("titleList.size:{}", rowList.size());
		reader.initTitle(rowList);
	}

	private void readerData(final List<String> rowList) {
		if (logger.isDebugEnabled()) {
			logger.debug("dataList.size:{}", rowList.size());
		}
		reader.putData(rowList);
//		//reader.putData(rowList);
//		cachedThreadPool.submit(new Runnable() {
//			@Override
//			public void run() {
//				atomicInteger.incrementAndGet();// +
//				if (logger.isDebugEnabled()) {
//					logger.debug("当前线程名：{} 任务队列数：{} 已经完成数：{}", Thread.currentThread().getName(), atomicInteger.get(),
//							countInteger.get());
//				}
//				try {
//					reader.putData(rowList);
//				} catch (Exception e) {
//					logger.error("exceld读取错误 ,MSG:{}", e.getMessage());
//				} finally {
//					atomicInteger.decrementAndGet();// -
//				}
//
//			}
//		});
	}
	
	/**
	 * 查询当前已经解析多少条的日志记录接口
	 * @return
	 */
	public int getCoun(){
		return this.countInteger.get();
	}
}
